<template>
	<view class="template-daily tn-safe-area-inset-bottom">
		<!-- 顶部自定义导航 -->
		<tn-nav-bar 
      :isBack="false" 
      :bottomShadow="false" 
      backgroundColor="none">
			<view 
        :style="{ 
          height: vuex_custom_bar_height +'px'
        }"
        class="custom-nav home-nav tn-flex tn-flex-row-left
          tn-flex-column-center">
				<view>
					<tn-tabs 
          :list="scrollList" 
          :current="current" 
          @change="tabChange" 
          activeColor="#262626"
          :showBar="false"
					inactiveColor="#FFFFFF" 
          :bold="true" 
          :fontSize="36">
					</tn-tabs>
				</view>
			</view>
		</tn-nav-bar>

		<view class="home-fixed">
			<view v-if="current==0" 
        class="swiper" 
        style="height:100vh;margin: 0 30rpx;"
				:style="{
          paddingTop: (vuex_custom_bar_height) +'px',
          paddingBottom: '120rpx'
        }">
				<daily-stack-swiper 
          ref="dailySwiper" 
          :list="swipeList" 
          :labels="labels"
          :labelsMap="labelsMap"
          @change="swipeChange"
          @showCpop="showCpop"
          @addLabel="praiseLabel"
          direction="vertical"
          :posting="posting"
          height="100%" 
          :switchRate="20" 
          :scaleRate="0.1" 
          :translateRate="0" 
          :opacityRate="20"
        >
				</daily-stack-swiper>
			</view>
			<view v-else class="" style="padding: 30vh 0;">
				<view class="tn-text-center" style="font-size: 200rpx;padding-top: 30rpx;">
					<text class="tn-icon-wea-wind tn-color-light"></text>
				</view>
				<view class="tn-color-light tn-text-center tn-text-lg">内容被台风吹走了</view>
			</view>
		</view>
    <tn-popup 
      v-model="showCom" 
      :borderRadius="23"
      :closeBtn="true"
      class="tn-tags-pop"
      :maskCloseable="true"
      mode="bottom" >
      <view class="popup-content tags-popup">
        <view class="tn-picker__content">
          <!-- 顶部 -->
          <view 
          class="tn-picker__content__header" 
          @touchmove.stop.prevent>
            <!-- 取消按钮 -->
            <!-- 标题 -->
            <view class="tn-picker__content__header__title">
              发布评论
            </view>
            <!-- 确认按钮 -->
          </view>
          <!-- 主体 -->
          <view class="tn-picker__content__body">
            <scroll-view scroll-y="true" class="scroll-Y labels-scroll-view">
              <view class="tn-flex tn-flex-wrap tn-labels-container">
                <view
                  @click="showAddLabel()"
                  class="tn-flex tn-three tn-flex-col-center tn-flex-row-center">
                  <view class="tn-margin-xs tn-flex tn-flex-col-center tn-flex-row-center
                   tn-radius bg-flex-shadow tn-shadow-blur">
                    <view class="tn-label-tag tn-label-add">
                      <text class="tn-icon tn-icon-add"></text>
                    </view>
                  </view>
                </view>
                <view class="tn-flex tn-three 
                tn-flex-col-center 
                tn-flex-row-center" 
                v-for="(item, index) in commentTags" 
                  :key="index" >
                  <view 
                    @click="postLabel(item.label)"
                    class="tn-flex 
                    tn-flex-center 
                    tn-margin-xs  
                    tn-radius 
                    bg-flex-shadow tn-shadow-blur">
                    <view class="tn-label-tag" 
                    :class="`tn-label-color-${index % 4}`">
                      {{item.label}}
                    </view>
                  </view>
                </view>
              </view>
            </scroll-view>
            <view class="tn-picker-bottom-wrap">
              <view class="tn-picker-bottom-container">
                <view class="tn-flex tn-three
                tn-flex-col-center 
                tn-flex-row-center" 
                v-for="(item, index) in offenTags.slice(0, 3)" 
                  :key="index" >
                  <view 
                    @click="postLabel(item)"
                    class="tn-flex 
                    tn-flex-center 
                    tn-margin-xs  
                    tn-radius 
                    bg-flex-shadow tn-shadow-blur">
                    <view class="tn-label-tag" 
                    :class="`common-label-color-${index % 4}`">
                      {{item}}
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </tn-popup>
    <tn-modal 
      v-model="showModel" 
      class="tags-model-box"
      :showCloseBtn="true"
      title="" :custom="true">
      <view class="custom-modal-content">
        <view class="tag-modal-title">自定义文字评论</view>
        <view>
          <tn-input v-model="labelForm" 
          maxLength="4"
          type="text" :border="true" :autoHeight="true" />
        </view>
        <view class="tags-modal-tips">
          输入文字  最多4个字符
        </view>
        <view>
          <tn-button 
          width="100%" 
          height="68rpx" 
          @click="addLabel()"
          backgroundColor="#EC5446"
          :border="false"
          fontSize="32"
          class="tn-custem-tag-btn"
          fontColor="#FFFFFF">确认</tn-button>
        </view>
      </view>
    </tn-modal>
    <tn-toast ref="toast"></tn-toast>
    <view v-if="pageLoading" class="loading-bg-container">
      <div class="lds-ring"><div></div><div></div><div></div><div></div></div>
    </view>
	</view>
</template>

<script>
	import {
		getHomeList,
		restaurantsLike,
    postRestaurantLabel,
    getRestaurantLabels
	} from '@/libs/js/home.js'
  import { mapState, mapGetters } from 'vuex';
  import { commentTags } from '@/libs/constant.js';
	import DailyStackSwiper from '@/pages/home/swiper/tn-stack-swiper.vue';
	export default {
		name: 'Daily',
		components: {
			DailyStackSwiper
		},
		data() {
			return {
				current: 0,
        pageLoading: false,
				scrollList: [{
						name: '附近'
					},
					{
						name: '饭搭子'
					},
				],
        showModel: false,
        labels: [],
        commentTags: commentTags,
        labelsMap: {},
        currentIndex: 0,
        realIndex: 0,
        labelForm: '',
        showCom: false,
        loaded: false,
        swipeActiveIndex: 0, // 当前轮播图激活索引
        swipeLength: 3, // 总的轮播图数量
				listQuery: {
					limit: 20,
					page: 1,
				},
        posting: false,
        loading: false,
				list: [],
				currentScroll: null
			}
		},
		computed: {
      ...mapGetters({
        offenTags: 'offenTags'
      }),
      swipeList() {
        // 获取当前值、下一个值、上一个值
        let currentValue = this.list[this.currentIndex]
        let nextValue = this.list[this.getDataIndex(this.currentIndex + 1)]
        let prevValue = this.list[this.getDataIndex(this.currentIndex - 1)]
  
        // 获取当前轮播索引对应的值、下个索引对应的值、上个索引对应的值
        let list = new Array(3)
        list[this.swipeActiveIndex] = currentValue || {foods: []};
        list[this.getSwipeIndex(this.swipeActiveIndex + 1)] = nextValue || {foods: []};
        list[this.getSwipeIndex(this.swipeActiveIndex - 1)] = prevValue || {foods: []};
        console.log(list);
        return list
      }
    },
    mounted() {
      this.initPage()
      this.commentTags.forEach((t) => {
        this.labelsMap[t.label] = t.bgClass;
      })
      if(this.offenTags.length == 0){
        commentTags.slice(0,3).map(c => {
          this.$store.commit('pushTags', c.label);
        })
      }
		},
		methods: {
       // 获取当前数据列表的索引
      getDataIndex(index) {
        if (index < 0) {
          // 小于零，返回数据列表末尾索引
          return this.list.length - 1
        } else if (index >= this.list.length) {
          // 等于（或大于，一般不会）数据列表长度，返回数据首位索引
          return 0
        } else {
          return index
        }
      },
      getSwipeIndex(index) {
        if (index < 0) {
          return this.swipeLength - 1
        } else if (index >= this.swipeLength) {
          return 0
        } else {
          return index
        }
      },
      swipeChange(index, realIndex) {
        let current = Number(index)
        this.realIndex = realIndex % this.list.length
        if ([1, 1 - this.swipeLength].includes(current - this.swipeActiveIndex)) {
          // 向左滑动
          this.currentIndex = this.getDataIndex(this.currentIndex + 1)
        } else {
          // 向右滑动
          this.currentIndex = this.getDataIndex(this.currentIndex - 1)
        }
        this.swipeActiveIndex = current;
        console.log(this.loaded, this.currentIndex, this.swipeActiveIndex, this.list.length);
        if (!this.loaded && this.currentIndex > this.list.length - 10) {
          console.log('loaded');
        	this.getList();
        }
        this.currentScroll = this.list[this.currentIndex];
        
        this.getLabels(this.currentScroll.id);
      },
      initPage(x) {
        const that = this;
        if(!x){
          this.pageLoading = true;
          setTimeout(() => {
            this.pageLoading = false;
          }, 3000)
        }
        console.log('homegetlocation')
        uni.getLocation({
        	type: 'gcj02',
          timeout: 1,
        	success: (res) => {
            console.log(res);
        		that.listQuery.lng = res.longitude;
        		that.listQuery.lat = res.latitude;
        		that.getList();
        	},
        	fail: function() {
            console.log('fil')
        		that.getList();
        	}
        })
      },
      getCount(c) {
        if(isNaN(c)){
          return 0
        }
       if(c> 99){
         return '99+'
       } 
       return c;
      },
      checkLength() {
        
      },
      addLabel() {
        if(this.labelForm && this.labelForm.length <= 4){
          this.postLabel(this.labelForm)
          this.labelForm = ''
        }else{
          this.$refs.toast.show({
            title: '',
            content: '请输入，不超过4位',
            icon: '',
            image: '',
            duration: 1500
          });
        }
      },
      showAddLabel() {
        this.showModel = true;
      },
      showCpop(item){
        this.showCom = true;
        this.currentScroll = item;
      },
			swipperChange(index, realIndex) {
        this.swiperIndex = index;
        this.realIndex = realIndex % this.list.length
        this.currentIndex = this.swiperIndex;
        console.log(this.loaded, this.realIndex, this.list.length);
				if (!this.loaded && this.realIndex > this.list.length - 10) {
					this.getList();
				}
        let showList = this.list.slice(realIndex - index, realIndex + 20 - index);
        if(index == 19){
          showList[0] = this.list[0];
        }
        
        if(this.list.length >= 20 && showList.length < 20){
          showList = showList.concat(this.list.slice(0, 20 - showList.length));
        }
        if(this.loaded && this.realIndex == this.list.length){
          this.realIndex = 0
        }
        if(this.loaded && this.list.length <= 20){
          this.currentScroll = this.list[this.swiperIndex];
        }else{
          // this.showList = showList;
          this.currentScroll = this.list[this.realIndex];
        }

        this.getLabels(this.currentScroll.id);
			},
      changeRealIdx(index){
        this.realIndex = index;
      },
      // 跳转
      tn(e) {
      	uni.navigateTo({
      		url: e,
      	});
      },
			// tab选项卡切换
			tabChange(index) {
				this.current = index
			},
      praiseLabel(label) {
        this.postLabel(label);
      },
      postLabel(label){
        this.posting = true;
        setTimeout(() => {
          this.posting = false;
        }, 400)
        postRestaurantLabel({
          label: label,
          restaurantsId: this.currentScroll.id
        }).then((res) => {
          if(res.code === 0){
            this.$store.commit('pushTags', label);
            this.getLabels(this.currentScroll.id);
            this.showCom = false;
            this.showModel = false;
            
          }else{
            this.$t.message.toast(res.msg);
          }
        })
      },
      getLabels(id) {
        getRestaurantLabels({
          restaurantsId: id
        }).then(res => {
          if(res.code === 0){
            this.labels = res.data.sort((a, b) => a.amount - b.amout);
          }
          this.showCom = false;
          this.showModel = false;
        })
      },
			getList() {
        console.log(this.listQuery)
        if(this.loading || this.loaded){
          return;
        }
        this.loading = true;
				
				getHomeList(this.listQuery).then(res => {
					if (res.code === 0 && res.data && res.data.length) {
						const t = res.data.map(r => {
							return {
								title: r.name,
								address: r.addresses,
								image: r.albums ? JSON.parse(r.albums)[0].url : '',
								foods: r.restaurantsMenuDish ? r.restaurantsMenuDish.slice(0, 4).map(a => {
									return {
										dishName: a.restaurantsMenuName,
										dishAlbums: a.albums ? JSON.parse(a.albums) : []
									}
								}) : [],
								restaurantsLikeBo: r.restaurantsLikeBo,
								...r
							}
						})
            if(this.listQuery.page == 1){
              this.list = t;
              // this.showList = t;
            }else{
              this.list = this.list.concat(t);
            }

            if(t.length < this.listQuery.limit){
              console.log(t.length, this.listQuery)
              this.loaded = true;
            }
            
						if (!this.currentScroll) {
							this.currentScroll = this.list[0];
              this.getLabels(this.currentScroll.id);
						}
					}else{
            this.loaded = true;
          }
          this.listQuery.page++;
          this.loading = false;
          setTimeout(() => {
            this.pageLoading = false;
          }, 1000);
				})
			},
			// 初始化轮播图容器
			initSwiperContainer() {
				// 获取底部tabbar信息
				this._tGetRect('.tabbar').then((res) => {
					if (!res.height) {
						setTimeout(() => {
							this.initSwiperContainer()
						}, 10)
						return
					}
					// 获取系统信息
					const systemInfo = uni.getSystemInfoSync()
					this.swiperContainerHeight = systemInfo.safeArea.height - res.height - 10
				})
			}
		}
	}
</script>
<style lang="scss" scoped>
  .tn-popup-class.tn-tags-pop{
    .tn-popup__close--top-right{
      top: 40rpx;
    }
  }
  .custom-nav {
  		height: 100%;
  	}

	.template-daily {

	}
  .uni-mask{
    background-color: rgba(0, 0, 0, 0.5);
  }
  
	/* 自定义颜色 */
	.tn-color-friend {
		color: #100B59;
	}

	.tn-color-light--dark {
		color: #57548A;
	}

	.tn-color-light {
		color: #A6A9CB;
	}
  .popup-content.tags-popup{
    .tn-popup__close--top-right{
      top: 40rpx;
    }
    .tn-picker {
      
      &__content {
        position: relative;
        .tn-three{
          width: 33.333333%;
        }
        .tn-label-add{
          background: #E8E8E8;
          color: #666;
        }
        &__header {
          position: relative;
          display: flex;
          flex-direction: row;
          width: 100%;
          height: 108rpx;
          background: #F6F6F6;
          padding: 0 40rpx;
          align-items: center;
          justify-content: center;
          box-sizing: border-box;
          font-size: 30rpx;
          border-radius: 16px 16px 0px 0px;
          &__btn {
            padding: 16rpx;
            box-sizing: border-box;
            text-align: center;
            text-decoration: none;
          }
          
          &__title {
            color: $tn-font-color;
          }
          
          &--cancel {
            color: $tn-font-sub-color;
          }
          
          &--confirm {
            color: $tn-main-color;
          }
        }
        .labels-scroll-view{
          height: 100%;
        }
        
        &__body {
          width: 100%;
          height: 640rpx;
          padding: 20rpx;
          position: relative;
          overflow-y: hidden;
          background-color: #FFFFFF;
          .tn-picker-bottom-wrap{
            position: absolute;
            bottom: 0;
            left: 0;
            right:0;
            height: 120rpx;
            background: #FFFFFF;
            box-shadow: 0px 0px 6px 1px rgba(0,0,0,0.16);
            border-radius: 0px 0px 0px 0px;
            width: 100%;
            padding: 0 20rpx;
            box-sizing: border-box;
            .tn-picker-bottom-container{
              width: 100%;
              height: 100%;
              display: flex;
              flex-direction: row;
              align-items: center;
            }
          }
          .tn-label-tag{
            white-space: nowrap;
            font-size: 40rpx;
            border-radius: 10rpx;
            line-height: 50rpx;
            text-align: center;
            padding: 10rpx 20rpx;
            width: 200rpx;
          }
          .tn-labels-container{
            overflow: scroll;
             padding-bottom: 140rpx;
          }
          &__view {
            height: 100%;
            box-sizing: border-box;
          }
          
          &__item {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
            font-size: 32rpx;
            color: $tn-font-color;
            padding: 0 8rpx;
            
            &--text {
              font-size: 24rpx;
              padding-left: 8rpx;
            }
          }
        }
      }
    }
  }

	/* 自定义导航栏内容 end */

	// 四个角渐变底色
	.home-fixed {
		position: fixed;
		top: 0;
		width: 100%;
		transition: all 0.25s ease-out;
		z-index: 100;
    background: linear-gradient(180deg, #FF8961 0%, rgba(255,255,255,0) 100%);
	}

	.home-fixed:before {
		content: "";
		position: absolute;
		top: 0;
		left: 0;
		bottom: 0;
		right: 0;
		z-index: -1;
		mask-image: linear-gradient(to bottom, transparent, black);
		background: linear-gradient(90deg, #FFFFFF, #FFFFFF);

	}

	/* 底部安全边距 start*/
	.tn-tabbar-height {
		min-height: 130rpx;
		height: calc(150rpx + env(safe-area-inset-bottom) / 2);
		height: calc(150rpx + constant(safe-area-inset-bottom));
	}

	/* 卡片轮播图 start */
	.swiper {
		border-radius: 10rpx;
		overflow: hidden;
	}

	/* 轮播图 end */
  .loading-bg-container{
    position: fixed;
    top: 0px;
    left: -144px;
    bottom: 106rpx;
    right: -144px;
    display: grid;
    place-items: center;
    place-content: center;
    /* grid-template-areas: "body"; */
    overflow: hidden;
    font-family: "Dela Gothic One", sans-serif;
    background-color: #fff;
    z-index: 999999;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    .lds-ring {
      display: inline-block;
      position: relative;
      width: 80px;
      height: 80px;
    }
    .lds-ring div {
      box-sizing: border-box;
      display: block;
      position: absolute;
      width: 64px;
      height: 64px;
      margin: 8px;
      border: 8px solid #fe9470;
      border-radius: 50%;
      animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;
      border-color: #fe9470 transparent transparent transparent;
    }
    .lds-ring div:nth-child(1) {
      animation-delay: -0.45s;
    }
    .lds-ring div:nth-child(2) {
      animation-delay: -0.3s;
    }
    .lds-ring div:nth-child(3) {
      animation-delay: -0.15s;
    }
    @keyframes lds-ring {
      0% {
        transform: rotate(0deg);
      }
      100% {
        transform: rotate(360deg);
      }
    }
  }
</style>